package cn.chousensei.chousenseiblog.controller;

import cn.chousensei.chousenseiblog.enums.RegisterErrorEnum;
import cn.chousensei.chousenseiblog.model.User;
import cn.chousensei.chousenseiblog.service.UserService;
import cn.chousensei.chousenseiblog.utils.MailUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class RegisterController {

    @Autowired
    UserService userService;

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/register")
    public String doRegister(@RequestParam("account") String account,
                             @RequestParam("password") String password,
                             @RequestParam("username") String username,
                             @RequestParam("checkPassword") String checkPassword,
                             Model model) {

        if (!MailUtils.isEmail(account)) {
            model.addAttribute("error", RegisterErrorEnum.ACCOUNT_ILLEGAL_INPUT.getMessage());
            return "register";
        }
        if (userService.isSame(account)) {
            model.addAttribute("error", RegisterErrorEnum.ACCOUNT_EXIST.getMessage());
            return "register";
        }
        if (StringUtils.isBlank(username)) {
            model.addAttribute("error", RegisterErrorEnum.USERNAME_IS_NULL.getMessage());
            return "register";
        }
        if (StringUtils.isBlank(password) || StringUtils.isBlank(checkPassword)) {
            model.addAttribute("error", RegisterErrorEnum.PASSWORD_IS_NULL.getMessage());
            return "register";
        }
        if (!password.equals(checkPassword)) {
            model.addAttribute("error", RegisterErrorEnum.PASSWORD_DIFFERENT.getMessage());
            return "register";
        }

        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        user.setUsername(username);

        userService.createOrUpdate(user);


        return "redirect:/";
    }
}
